import {Component, DoCheck, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
}) /*变更检测机制DoCheck*/
export class ChildComponent implements OnInit, OnChanges, DoCheck {
  @Input()
  greeting: string;

  @Input()
  user: { name: string };

  message: string;

  /*变更前的用户名发*/
  olderUsername: string;

  /*检测是否发生变化*/
  changeDetected: boolean = false;

  noChangeCount: number = 0;

  constructor() {
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log(JSON.stringify(changes, null, 2));
  }

  ngOnInit() {
  }

  ngDoCheck(): void {

    /*牛逼之人必有牛逼之处*/
    if (this.user.name !== this.olderUsername) {
      this.changeDetected = true;
      console.log('DoCheck:user.name' + this.olderUsername + '变为' + this.user.name);
      this.olderUsername = this.user.name;
    }

    /*我去了这些都是天才*/
    if (this.changeDetected) {
      this.noChangeCount = 0;
    } else {
      this.noChangeCount = this.noChangeCount + 1;
      this.olderUsername = this.user.name;
      console.log('DoCheck:user.name方法没有被变化时，ngDoCheck方法已经调' + this.noChangeCount + '次');
    }

    this.changeDetected = false ;
  }

}
